<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <div class="flex justify-center">
          <ImageInput v-model="formValue.avatar" />
        </div>
        <n-form-item label="昵称" path="name">
          <n-input v-model:value="formValue.name" placeholder="请输入昵称" />
        </n-form-item>

        <n-form-item label="联系电话" path="phone">
          <n-input placeholder="请输入联系电话" v-model:value="formValue.phone" />
        </n-form-item>

        <n-form-item label="联系地址" path="address">
          <n-input v-model:value="formValue.address" type="textarea" placeholder="请输入联系地址" />
        </n-form-item>

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit()">更新基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import ImageInput from './ImageInput.vue';
  import { compileUser } from '@/api/system/user';
  import { useUserStore } from '@/store/modules/user';

  const userStore = useUserStore();
  const { user } = userStore.user;

  const rules = {
    name: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
    mobile: {
      required: true,
      message: '请输入联系电话',
      trigger: 'input',
    },
  };
  const formRef: any = ref(null);
  const message = useMessage();
  const formValue: {
    avatar: string | File;
    name: string;
    phone: string;
    address: string;
  } = reactive({
    avatar: user.avatar,
    name: user.name,
    phone: user.phone,
    address: user.address,
  });

  const formSubmit = async () => {
    const formData = new FormData(); // 将 formValue 转换为 formData
    Object.entries(formValue).forEach(([k, v]) => {
      if (k == 'avatar' && v instanceof File) {
        formData.append(k, v, v.name);
      } else formData.append(k, v);
    });
    formRef.value.validate(async (errors) => {
      if (!errors) {
        const data = await compileUser(formValue);
        message.success('验证成功');
        userStore.setUser(data.result);
        // console.log(data);
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  };
</script>
